package net.pimpas.communication.message.impl;

import java.util.Calendar;
import java.util.Date;

import net.pimpas.communication.message.Message;
import net.pimpas.locking.serviceprovider.LockingServiceProviderFactoryImpl;

public class DefaultMessageImpl implements Message {
	
	private Integer readCount;
	private final Date createdTime = Calendar.getInstance().getTime(); 
	private Object object;
	
	public DefaultMessageImpl(final Object object) {
		this.setReadCount(0);
		this.setObject(object);
	}

	public Date getCreatedTime() {
		return this.createdTime;
	}

	public int getReadCount() {
		try {
			LockingServiceProviderFactoryImpl.getLockingServiceProvider()
			.lockRead(this.readCount);
			
			return this.readCount;
		} finally {
			LockingServiceProviderFactoryImpl.getLockingServiceProvider()
			.unlockRead(this.readCount);
		}
	}

	public Object read() {
		try {
			LockingServiceProviderFactoryImpl.getLockingServiceProvider()
			.lockWrite(this);
			this.setReadCount(this.getReadCount()+1);
		} finally {
			LockingServiceProviderFactoryImpl.getLockingServiceProvider()
			.unlockWrite(this);
		}

		return this.getObject();
	}

	public void setReadCount(Integer readCount) {
		this.readCount = readCount;
	}

	public Object getObject() {
		return object;
	}

	public void setObject(Object object) {
		this.object = object;
	}
}